package com.itzsj.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzsj.common.properties.JwtProperties;
import com.itzsj.common.result.Result;
import com.itzsj.common.utils.JWTUtil;

import com.itzsj.mapper.CommonMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource(name = "jwtProperties", type = JwtProperties.class)
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) return true;

        String url = request.getRequestURL().toString();
        log.info("request url:{}", url);

        if (url.contains("login")) return true;

        String jwtToken = request.getHeader("jToken");

        if (jwtToken == null || jwtToken.isEmpty()) {
            log.info("jwt token is empty");
            response.getWriter().write("NO_LOGIN");
            return false;
        }

        try {
            Claims claims = JWTUtil.parseJWT(jwtToken, jwtProperties.getSecretKey());
            log.info("jToken: {}", claims);
            /*
            String account = claims.get("ACCOUNT",String.class);
            String password = claims.get("PASSWORD",String.class);
            */
            return true;
        } catch (Exception exception) {
            response.setStatus(401);
            return false;
        }

    }

}
